package cn.eng.org.service.impl;

import cn.eng.basic.service.impl.BaseServiceImpl;
import cn.eng.org.domain.Department;
import cn.eng.org.mapper.DepartmentMapper;
import cn.eng.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    /**
     * 部门级联树业务
     * @return
     */
    @Override
    public List<Department> deptTree() {
            //先查询所有的部门列表
        List<Department> departments = departmentMapper.loadAll();
        //把所有的部门列表装进一个map中 ,k 表示id v表示每一个部门的对象
        Map<Long,Department> map=new HashMap<>();
        for (Department department:departments) {
            map.put(department.getId(),department);
        }
        List<Department> deptTree=new ArrayList<>();
        for (Department department:departments) {
            //判断如果getParent_id 为null 表示是父级部门
            if(department.getParent_id()==null){
                deptTree.add(department);
            }else {
                //如果不是父级部门就是子级部门 ,先获取父级部门的id
                Long parent_id = department.getParent_id();
                //通过id 在map里面获取父级部门的对象
                Department parentDepartment= map.get(parent_id);
                //如果父级部门不为null 就装进Department 的children 集合中
                if(parentDepartment!=null){
                    parentDepartment.getChildren().add(department);
                }
            }
        }
        return deptTree;
    }
}
